﻿using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MESMian.Common.Helpers
{
    public static class CheckCodeHelper
    {
        public static Bitmap CenCheckCode(int count, int width, int height, out string checkCode)
        {
            Bitmap bitmap = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bitmap);
            g.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height);

            string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            Random r = new Random();
            StringBuilder sb = new StringBuilder();
            Font font = new Font(FontFamily.GenericSerif, 24, FontStyle.Bold, GraphicsUnit.Pixel);


            Color[] colors = {
                Color.Blue, Color.Green, Color.Red, Color.Orange,
                Color.Purple,Color.Yellow,Color.Chocolate,Color.Brown,
                Color.Gold, Color.Black, Color.Gray, Color.DarkBlue
            };

            for (int i = 0; i < count; i++)
            {
                // 产生颜色的随机索引 
                int colorIndex = r.Next(0, colors.Length); // 生成一个0到11的随机数
                // 产生是字符的随机索引
                int letterIndex = r.Next(0, letters.Length);
                string letter = letters[letterIndex].ToString();
                sb.Append(letter);
                g.DrawString(letter, font, new SolidBrush(colors[colorIndex]), i * 35, r.Next(0, 12));
            }

            checkCode = sb.ToString(); //先保存，将来验证与用户输入是否一致


            // 生成干扰线条，混淆背景
            Pen[] pens = {
                new Pen(Color.Blue, 2){DashStyle=DashStyle.Solid},
                new Pen(Color.Green, 2){DashStyle=DashStyle.Dash},
                new Pen(Color.Red, 2){DashStyle=DashStyle.Dot},
                new Pen(Color.Orange, 2){DashStyle=DashStyle.DashDot},
                new Pen(Color.Orchid, 2){DashStyle=DashStyle.DashDotDot},
                new Pen(Color.Yellow, 2){DashStyle=DashStyle.Solid},
                new Pen(Color.Chocolate, 2){DashStyle=DashStyle.Dash},
                new Pen(Color.Brown, 2){DashStyle=DashStyle.Dot},
                new Pen(Color.Gold, 2){DashStyle=DashStyle.DashDot},
                new Pen(Color.Black, 2){DashStyle=DashStyle.DashDotDot},
                new Pen(Color.Gray, 2){DashStyle=DashStyle.DashDot},
                new Pen(Color.DarkBlue, 2){DashStyle=DashStyle.DashDotDot}
            };
            for (int i = 0; i < 10; i++)
            {
                int penIndex = r.Next(0, 12); // 生成一个0到11的随机数

                g.DrawLine(pens[penIndex], new Point(r.Next(0, width), r.Next(0, height)), new Point(r.Next(0, width), r.Next(0, height)));
            }

            return bitmap;
        }
    }
}
